package com.alex.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alex.server.pojo.*;
import com.alex.server.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.internal.dynalink.linker.LinkerServices;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author alex
 * @since 2022-08-30
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    public IEmployeeService employeeService;
    @Autowired
    public IPoliticsStatusService politicsStatusService;
    @Autowired
    public IJoblevelService joblevelService;
    @Autowired
    public INationService nationService;
    @Autowired
    public IPositionService positionService;
    @Autowired
    public IDepartmentService departmentService;
    @ApiOperation(value = "查询所有员工,并且分页")
    @GetMapping
    public RespPageBean getEmployee(@RequestParam (defaultValue = "1") Integer currentPage
            , @RequestParam(defaultValue = "10") Integer size
            , Employee employee
            ,LocalDate[] beginDataSource ){
        return employeeService.getEmployeeByPage(currentPage,size,employee,beginDataSource);
    }
    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/ploitic/")
    public List<PoliticsStatus> politicsStatuses(){
        List<PoliticsStatus> list = politicsStatusService.list();
        return list;
    }
    @ApiOperation(value = "获取所有职称")
    @GetMapping("/jobLevel")
    public List<Joblevel> joblevels(){
        List<Joblevel> list = joblevelService.list();
        return list;
    }
    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> nations(){
        return  nationService.list();
    }
    @ApiOperation(value = "获取所有职位")
    @GetMapping("/Position")
    public List<Position> positions(){
        return positionService.list();
    }
    @ApiOperation(value = "获取所有部门")
    @GetMapping("departMent")
    public List<Department> departments(){
        return departmentService.getAllDepartments();
    }
    @ApiOperation(value = "获取工号")
    @GetMapping("/maxWorkId")
    public RespBean maxWorkId(){
        return employeeService.getMaxWorkId();
    }
    @ApiOperation(value = "添加员工")
    @PostMapping
    public RespBean addEmp(@RequestBody Employee employee){
        return employeeService.addEmp(employee);
    }
    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public RespBean upEmp(@RequestBody Employee employee){
        return employeeService.upEmp(employee);
    }
    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return RespBean.success("删除成功");
        }else{
            return RespBean.error("删除失败");
        }
    }
    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export",produces ="application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        //获取所有的员工数据
        List<Employee> employee = employeeService.getEmployee(null);
        System.out.println(employee.get(1).getJoblevel().getName());
        //导出参数
        ExportParams params=new ExportParams("员工表","员工表", ExcelType.HSSF);
        //excel导出工具类
        Workbook sheets = ExcelExportUtil.exportExcel(params, Employee.class, employee);
        //通过流的方式导出数据
        ServletOutputStream outputStream=null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition" ,"attachment;filename="+ URLEncoder.encode("员工表.xls","utf-8"));
            outputStream= response.getOutputStream();
            sheets.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    @ApiOperation(value = "导入excel表")
    @PostMapping("/import")
    public RespBean importRole(@RequestParam MultipartFile file){
        ImportParams params=new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        //去数据库查询所有nation集合
        List<Nation> list = nationService.list();//
        //政治面貌集合
        List<PoliticsStatus> politics = politicsStatusService.list();
        //职称集合
        List<Joblevel> joblevelList = joblevelService.list();
        //职位集合
        List<Position> positionList = positionService.list();
        //部门集合
        List<Department> departmentList = departmentService.list();
        try {
            List<Employee> employeeList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            employeeList.forEach(employee -> {
                //先创建一个nation
                Nation nation = new Nation(employee.getNation().getName());
                //通过重写equal跟hashcode方法,用nationName进行比较是否相等,相等的话返回其所在地址
                int index = list.indexOf(nation);
                //根据地址取寻找该nation得到其id
                Integer nationId = (list.get(index)).getId();
                //获取并设置民族的id
                employee.setNationId(nationId);
                PoliticsStatus politicsStatus = new PoliticsStatus(employee.getPoliticsStatus().getName());
                Integer politicId = politics.get(politics.indexOf(politicsStatus)).getId();
                //获取并设置政治面貌的id
                employee.setPoliticId(politicId);
                //获取并设置职称的id
                Joblevel joblevel = new Joblevel(employee.getJoblevel().getName());
                int index1 = joblevelList.indexOf(joblevel);
                employee.setJobLevelId(joblevelList.get(index1).getId());
                //获取并设置职位id
                employee.setPosId(positionList.get(positionList.
                        indexOf(new Position(employee.getPosition().getName()))).getId());
                //获取并设置部门id
                employee.setDepartmentId(departmentList.get(departmentList.
                        indexOf(new Department(employee.getDepartment().getName()))).getId());
            });
            if(employeeService.saveBatch(employeeList)){
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }
}
